package parsing.productions;

import java.util.Random;

import parsing.InvalidSyntaxException;

public class Rel extends MutableNode {
	// Invariant for children: empty.
	
	/**<*/
	public static final int LT  = 1;
	/**<=*/
	public static final int LE  = 2;
	/**=*/
	public static final int EQ  = 3;
	/**>=*/
	public static final int GE  = 4;
	/**>*/
	public static final int GT  = 5;
	/**!=*/
	public static final int NE  = 6;
	
	private int type;

	/**
	 * Constructor: creates an instance of Rel that is a comparison operation.
	 * @param operation type of Rel.
	 * Checks: operation is LT, LE, EQ, GE, GT, or NE.
	 */
	public Rel(int operation) {
		boolean b= (operation==LT) || (operation==LE) || (operation==EQ) || (operation==GE) || (operation==GT) || (operation==NE);
		if (!b) {
			throw new InvalidSyntaxException("The only types this Rel can have are LT, LE, EQ, GE, GT, or NE");
		}
		type= operation;
	}
	
	public int getType(){
		return type;
	}

	@Override
	public int size() {
		return 1;
	}

	@Override
	public void prettyPrint(StringBuffer sb) {
		switch(type){
		case LT: sb.append("< "); break;
		case LE: sb.append("<= "); break;
		case EQ: sb.append("= "); break;
		case GE: sb.append(">= "); break;
		case GT: sb.append("> "); break;
		case NE: sb.append("!= "); break;
		}
	}

	@Override
	public void mutate(Program genome) {
//		StringBuffer sb = new StringBuffer();
//		prettyPrint(sb);
//		sb.append("was changed to ");
		Random rnd = new Random();
		int newType;
		do{
			newType = rnd.nextInt(6) + 1;
		} while (newType == type);
		type = newType;
//		prettyPrint(sb);
//		System.out.println(sb);
	}

	@Override
	public Node duplicate() {
		return new Rel(type);
	}

	/**
	 * Checks if this Rel is the same as n
	 * @param n the node to check against
	 * @return true if n is a Rel and its type is the same as this one's
	 */
	@Override
	public boolean equals(Node n){
		if(!(n instanceof Rel))
			return false;
		Rel rNode = (Rel) n;
		if(type != rNode.type)
			return false;
		return true;
	}
}
